
let img_selected = new Image();
img_selected.loaded = false;
img_selected.src = 'imgs/tile_selected.png';
img_selected.onload = function(){
    img_selected.loaded = true;
};

class TileDrawable{
    constructor(tileType,rowIdx,colIdx){
        this.tileType = tileType;
        this.rowIdx = rowIdx;
        this.colIdx = colIdx;
        this.bSelected = false;
    }
    draw(ctx){
        let img = _getTileImage(this.tileType);
        let cx = this.colIdx * C_Tile_Width;
        let cy = this.rowIdx * C_Tile_Height;
        if(this.bSelected){
            if(img_selected){
                let ixy = cxy_to_iso(cx,cy);
                ctx.drawImage(img_selected,ixy.x - 32,ixy.y);
            }
        }else{
            if(img){
                let ixy = cxy_to_iso(cx,cy);
                ctx.drawImage(img,ixy.x - 32,ixy.y);
            }
        }
    }
}

class Map{
    constructor(){
        let map = [
            [1,1,1,1,1,1,1,1,1,1,1,1],
            [1,0,0,0,0,1,1,1,1,1,1,1],
            [1,0,0,0,0,1,1,1,1,1,1,1],
            [1,0,0,0,0,1,1,1,1,1,1,1],
            [1,0,0,0,0,1,1,1,1,1,1,1],
            [1,0,0,0,0,1,1,1,1,1,1,1],
            [1,0,0,0,0,1,1,1,1,1,1,1],
            [1,0,0,0,0,1,1,1,1,1,1,1],
            [1,0,0,0,0,1,1,1,1,1,1,1],
            [1,1,1,1,1,1,1,1,1,1,1,1],
        ];

        let mapTileObj = [];
        for(let rowIdx = 0,len = map.length; rowIdx < len; ++rowIdx){
            mapTileObj[rowIdx] = [];
            for(let colIdx = 0,clen = map[rowIdx].length;colIdx < clen; ++colIdx){
                let tileType = map[rowIdx][colIdx];
                mapTileObj[rowIdx][colIdx] = new TileDrawable(tileType,rowIdx,colIdx);
            }
        }
        this.mapTiles = mapTileObj;

        this.selectedTile = null;
    }
    draw(ctx){
        let mapTiles = this.mapTiles;
        mapTiles.forEach(mapRows=>{
            mapRows.forEach(tile=>{
                tile.draw(ctx);
            })
        })
    }

    selectTile(rowIdx,colIdx){
        let tile = this.getTile(rowIdx,colIdx);
        if(tile){
            console.log(`select tile. rowIdx:${rowIdx},colIdx:${colIdx}`);
            if(this.selectedTile){
                this.selectedTile.bSelected = false;
            }
            tile.bSelected = true;
            this.selectedTile = tile;
        }
    }

    getTile(rowIdx,colIdx){
        if(rowIdx < 0 || rowIdx >= this.mapTiles.length){
            return null;
        }
        if(colIdx < 0 || colIdx >= this.mapTiles[0].length){
            return null;
        }
        return this.mapTiles[rowIdx][colIdx];
    }
}
